﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FastData;
using System.Threading;

namespace MglMES
{
    public partial class MesInfoConfig : MyControlBase
    {

        //"MesTimeOut", "MESheartbeatAdress", "devicestateAdress", "deviceState"
        public MesInfoConfig():base()
        {
            timeOut = new VarSave<int>("MesTimeOut");
            heartbeatAdress = new VarSave<string>("MESheartbeatAdress");
            devicestateAdress = new VarSave<string>("devicestateAdress");
            deviceCode = new VarSave<string>("deviceCode");
            dayTimeStart = new VarSave<DateTime>("dayTimeStart");
            dayTimeOver = new VarSave<DateTime>("dayTimeOver");
            nightTimeStart = new VarSave<DateTime>("nightTimeStart");
            nightTimeOver = new VarSave<DateTime>("nightTimeOver");
            plcAlarmAddressList = new VarSave<List<string>>("plcAlarmAddressList");
            mesInteractionTime = new VarSave<int>("mesInteractionTime");
           
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    TimeSpan timeSpan1 = DateTime.Now - new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, dayTimeStart.Value.Hour, dayTimeStart.Value.Minute, 0);
                    TimeSpan timeSpan2 = DateTime.Now - new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, dayTimeOver.Value.Hour, dayTimeOver.Value.Minute, 0);
                    TimeSpan timeSpan = nightTimeStart.Value - dayTimeOver.Value;
                    if (timeSpan1.Ticks > 0 - timeSpan.Ticks / 2 && timeSpan2.Ticks < timeSpan.Ticks / 2)
                    {
                        shift = "白班";
                    }
                    else
                    {
                        shift = "夜班";
                    }

                    if (DateTime.Now > new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, dayTimeStart.Value.Hour, dayTimeStart.Value.Minute, 0).AddTicks(-timeSpan.Ticks / 2))
                    {
                        shiftDate = DateTime.Now.ToString("yyyy-MM-dd");

                    }
                    else
                    {
                        shiftDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                    }
                    Thread.Sleep(1000);
                }
            });

            InitializeComponent();
        }


        protected override void Timer_Tick(object sender, EventArgs e)
        {
            label14.Text = $"班次日期：{shiftDate},班次：{shift}";
            if (InterfaceClient.PLCConnectStatus)
            {
                label15.BackColor = Color.LimeGreen;
                label15.Text = "PLC在线";
            }
            else
            {
                label15.BackColor = Color.Red;
                label15.Text = "PLC离线";
            }

            if (InterfaceClient.MESConnectStatus)
            {
                label16.BackColor = Color.LimeGreen;
                label16.Text = "MES在线";
            }
            else
            {
                label16.BackColor = Color.Red;
                label16.Text = "MES离线";
            }

            if (InterfaceClient.SQLConnectStatus)
            {
                label17.BackColor = Color.LimeGreen;
                label17.Text = "SQL在线";
            }
            else
            {
                label17.BackColor = Color.Red;
                label17.Text = "SQL离线";
            }
        }




        private void button1_Click(object sender, EventArgs e)
        {
            heartbeatAdress.Value = textBox1.Text;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            devicestateAdress.Value = textBox2.Text;
        }
        private void button3_Click(object sender, EventArgs e)
        {
            deviceCode.Value = textBox3.Text;
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (numericUpDown1.Value < mesInteractionTime.Value)
            {
                MessageBox.Show("MES超时时间不能小于MES心跳交互时间间隔！");
                numericUpDown1.Value = timeOut.Value;
                return;
            }
            timeOut.Value = (int)numericUpDown1.Value;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            dayTimeStart.Value = timeInput1.Timepanel;
            dayTimeOver.Value = timeInput2.Timepanel;
        }


        private void button6_Click(object sender, EventArgs e)
        {
            nightTimeStart.Value = timeInput3.Timepanel;
            nightTimeOver.Value = timeInput4.Timepanel;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if(listBox1.Items.Contains(textBox4.Text))
            {
                MessageBox.Show($"{textBox4.Text}已经存在!");
                return;
            }


            listBox1.Items.Add(textBox4.Text);
            string[] arr = new string[listBox1.Items.Count];
            listBox1.Items.CopyTo(arr, 0);
            plcAlarmAddressList.Value = arr.ToList<string>();
        }

        private void listBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItems.Count > 0)
                textBox4.Text = listBox1.SelectedItems[0].ToString();
        }


        private void button8_Click(object sender, EventArgs e)
        {

            if (listBox1.SelectedItems.Count == 0)
            {
                MessageBox.Show($"请选择一项！");
                return;
            }

            listBox1.Items.Remove(listBox1.SelectedItems[0]);
            string[] arr = new string[listBox1.Items.Count];
            listBox1.Items.CopyTo(arr, 0);
            plcAlarmAddressList.Value = arr.ToList<string>();
        }


        private void button9_Click(object sender, EventArgs e)
        {
            if (timeOut.Value < numericUpDown2.Value)
            {
                MessageBox.Show("MES心跳交互时间间隔不能大于MES超时时间！");
                numericUpDown2.Value = mesInteractionTime.Value;
                return;
            }
            mesInteractionTime.Value = (int)numericUpDown2.Value;
        }

        private void MESInfoConfig_Load(object sender, EventArgs e)
        {
            numericUpDown1.Value = timeOut.Value;
            numericUpDown2.Value = mesInteractionTime.Value;
            textBox1.Text = heartbeatAdress.Value;
            textBox2.Text = devicestateAdress.Value;
            textBox3.Text = deviceCode.Value;
            timeInput1.Timepanel = dayTimeStart.Value;
            timeInput2.Timepanel = dayTimeOver.Value;
            timeInput3.Timepanel = nightTimeStart.Value;
            timeInput4.Timepanel = nightTimeOver.Value;
            listBox1.Items.AddRange(plcAlarmAddressList.Value.ToArray());

            //doubleBufferListView1.Items.Add("");




        }






        public VarSave<int> timeOut;
        /// <summary>
        /// pc写入plc
        /// </summary>
        public VarSave<string> heartbeatAdress;
        /// <summary>
        /// pc读取plc
        /// </summary>
        public VarSave<string> devicestateAdress;
        /// <summary>
        /// 设备编码
        /// </summary>
        public VarSave<string> deviceCode;

        public VarSave<DateTime> dayTimeStart;

        public VarSave<DateTime> nightTimeStart;

        public VarSave<DateTime> dayTimeOver;

        public VarSave<DateTime> nightTimeOver;

        public VarSave<int> mesInteractionTime;

        public VarSave<List<string>> plcAlarmAddressList;

        public bool AlarmUploadSign = false;


        public string shiftDate;

        public string shift;

        private void button12_Click(object sender, EventArgs e)
        {
            InterfaceClient.SetPLCConnectionForm();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            InterfaceClient.SetSQLConnectionForm();
        }

        private void button10_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFile = new OpenFileDialog();
                openFile.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
                openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                openFile.Multiselect = false;
                if (openFile.ShowDialog() == DialogResult.Cancel) return;
                var filePath = openFile.FileName;
                DataSet dataSet = ExcelHelper.WorksheetToDataSet(filePath);
                InterfaceClient._newSQL.SqlClient.Delete("DELETE FROM PLC_Alarm_Config WHERE 0=0");
                for (int j = 0; j < dataSet.Tables[0].Rows.Count; j++)
                {
                    long a = 0;
                    string[] STR = dataSet.Tables[0].Rows[j].Field<string>("地址 (读取地址)").Split('/');
                    InterfaceClient._newSQL.SqlClient.Insert("PLC_Alarm_Config", new string[] { "AlarmCode", "AlarmContent" }, new object[] { STR[2], dataSet.Tables[0].Rows[j].Field<string>("内容") }, ref a);
                }
                MessageBox.Show($"已经重新配置{ dataSet.Tables[0].Rows.Count}条报警信息！");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            InterfaceClient.SetSocketConnectionForm();
        }
    }
}
